/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-11-11 09:51:56
 * Last Modified: 2016-09-08 17:25:38
 * File Name: controllers/captcha.go
 * Description:
 */
package controllers

import (
	"encoding/json"

	"passport/captcha"
	"passport/errorcode"

	"doubimeizhi.com/utility"

	log "github.com/cihub/seelog"
)

type CaptchaController struct {
	URLSignController
}

/*
	请求发送验证码
*/
func (p *CaptchaController) MobileCaptchaSend() {
	defer p.Output("MobileCaptchaSend")

	body := p.Ctx.Input.RequestBody
	log.Debugf("recv body: %s", string(body))
	reqBody := &captcha.SendCapchaReq{}
	if err := json.Unmarshal(body, reqBody); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}
	reqBody.AppKey = p.AppKey

	code, msg := captcha.GetCaptchaService().SendCaptchaForMobile(reqBody)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

/*
	验证码验证
*/
func (p *CaptchaController) MobileCaptchaValidate() {
	defer p.Output("MobileCaptchaValidate")

	body := p.Ctx.Input.RequestBody
	reqBody := &captcha.ValidateCaptchaReq{}
	if err := json.Unmarshal(body, reqBody); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
	}

	code, msg := captcha.GetCaptchaService().ValidateCaptchaForMobile(reqBody)
	p.Resp["code"] = code
	p.Resp["msg"] = msg
}

/*
	查询对应的验证码
*/
func (p *CaptchaController) GetCapatchaInfo() {
	defer p.Output("GetCapatchaInfo")
	if !p.PriorityVisit() {
		p.Resp["code"] = errorcode.EC_GL_INVALID_IP
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_IP)
		return
	}
	mobile := p.GetString("mobile", "")
	bid, _ := p.GetInt("bid", 0)
	if !utility.IsValidMainlandMobile(mobile) {
		p.Resp["code"] = errorcode.EC_CAPTCHA_INVALID_MOBILE_NUMBER
		p.Resp["msg"] = "invalid mobile number"
		return
	}

	if !captcha.IsValidCaptchaType(uint(bid)) {
		p.Resp["code"] = errorcode.EC_CAPTCHA_NOT_SUPPORT_BID
		p.Resp["msg"] = "NOT support bid"
		return
	}

	ci, ttl, err := captcha.GetCaptchaService().GetCaptchaInfoItem(mobile, uint(bid))
	if err != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = err.Error()
		return
	}

	if ci == nil {
		p.Resp["code"] = errorcode.EC_CAPTCHA_NOT_EXISTS
		p.Resp["msg"] = "手机没有验证码"
		return
	}
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["mobile"] = mobile
	p.Resp["captcha"] = ci.Captcha
	p.Resp["send_tick"] = ci.SendTick
	p.Resp["send_times"] = ci.Times
	p.Resp["captcha_ttl"] = ttl
}
